package com.syj.collect.model;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.github.barteksc.pdfviewer.PDFView;
import com.google.gson.Gson;
import com.syj.collect.app.R;
import com.syj.collect.base.BaseActivity;
import com.syj.collect.entry.UserInfoBean;
import com.syj.collect.http.ApiServise;
import com.syj.collect.http.BaseObserver;
import com.syj.collect.http.BaseRequest;
import com.syj.collect.utils.LoadingDialog;
import com.syj.collect.utils.SPUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public  class PdfActivity extends BaseActivity {
    private PDFView pdfView;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf);
        pdfView=findViewById(R.id.pdf_view);
        initTitle("我的月报");
        String url = getIntent().getStringExtra("url");
        String replaceurl = url.replace(".docx", ".pdf");
        download(replaceurl);
        loadingDialog = new LoadingDialog(this);
        loadingDialog.create();
        loadingDialog.show();
    }

    private void download(String replaceurl) {

        // Log.e("1", str);

        BaseRequest.getInstance().getApiServise().download(ApiServise.PDF +replaceurl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ResponseBody>() {

                    @Override
                    public boolean onSuccess(ResponseBody body) {

                        writeResponseBodyToDisk(body);
                        loadingDialog.dismiss();
                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                    loadingDialog.dismiss();
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }

    private boolean writeResponseBodyToDisk(ResponseBody body) {

        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String fileName="text.pdf";

        File pdfFile = new File(savePath, fileName);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            byte[] fileReader = new byte[1024];
            // 获取文件大小
            long fileSize = body.contentLength();
            long fileSizeDownloaded = 0;
            inputStream = body.byteStream();
            outputStream = new FileOutputStream(pdfFile);

            // byte转Kbyte
            BigDecimal bd1024 = new BigDecimal(1024);
            int totalByte = new BigDecimal(fileSize).divide(bd1024, BigDecimal.ROUND_HALF_UP).setScale(0).intValue();

            // 只要没有取消就一直下载数据
            while (inputStream!=null) {
                int read = inputStream.read(fileReader);
                if (read == -1) {
                    // 下载完成
                 pdfView.fromFile(pdfFile)
                .defaultPage(0)
                .swipeHorizontal(false)
                .load();
                    break;
                }
                outputStream.write(fileReader, 0, read);

            }
            outputStream.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}
